import 'package:flutter_admin/api/odoo/sale_inquiry_product_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_form.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_product.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_product_edit.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';

// 询价表明细
class SaleInquiryProductList extends StatefulWidget {
  SaleInquiryForm? saleInquiryForm;
  SaleInquiryProductList({required this.saleInquiryForm, Key? key})
      : super(key: key);

  @override
  _SaleInquiryProductList createState() => _SaleInquiryProductList();
}

class _SaleInquiryProductList extends State<SaleInquiryProductList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct();
  List<SaleInquiryProduct> selectedList = [];
  List tableList = [];
  String? inquiryId = '';
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadData();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '询价单编号',
            enable: false,
            value: saleInquiryProduct.inquiryNo,
            onSaved: (v) {
              saleInquiryProduct.inquiryNo = v;
            },
          ),
          CryInput(
            width: 280,
            label: '询价单位',
            enable: false,
            value: saleInquiryProduct.partnerName,
            onSaved: (v) {
              saleInquiryProduct.partnerName = v;
            },
          ),
          CryInput(
            width: 280,
            label: '业务员',
            enable: false,
            value: saleInquiryProduct.userName,
            onSaved: (v) {
              saleInquiryProduct.userName = v;
            },
          ),
        ],
      ),
    );
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('产品编码(图号)')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('技术要求')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('单价(元)')),
        DataColumn(label: Text('小计(元)')),
        DataColumn(label: Text('退税率')),
        DataColumn(label: Text('销售单价（外币）')),
        DataColumn(label: Text('核算含税价格（元）')),
        DataColumn(label: Text('核算不含税价格（元）')),
        DataColumn(label: Text('单位补税及税金附加（元）')),
        DataColumn(label: Text('单项利润率%')),
        DataColumn(label: Text('单项换汇成本')),
      ],
      getCells: (m) {
        SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct.fromMap(m);
        return [
          DataCell(Text(saleInquiryProduct.productCode ?? '--')),
          DataCell(Text(saleInquiryProduct.productName ?? '--')),
          DataCell(Text(saleInquiryProduct.description ?? '--')),
          DataCell(Text(saleInquiryProduct.technicalRequirement ?? '--')),
          DataCell(Text(saleInquiryProduct.comment ?? '--')),
          DataCell(Text(saleInquiryProduct.unit ?? '--')),
          DataCell(Text(saleInquiryProduct.quantity != null
              ? saleInquiryProduct.quantity.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.unitPrice != null
              ? saleInquiryProduct.unitPrice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.sum ?? '--')),
          DataCell(Text(saleInquiryProduct.taxrate != null
              ? saleInquiryProduct.taxrate.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.foreignprice != null
              ? saleInquiryProduct.foreignprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.taxinclusiveprice != null
              ? saleInquiryProduct.taxinclusiveprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.notaxinclusiveprice != null
              ? saleInquiryProduct.notaxinclusiveprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.taxsurcharges != null
              ? saleInquiryProduct.taxsurcharges.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.singleprofitmargin != null
              ? saleInquiryProduct.singleprofitmargin.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.summarycost != null
              ? saleInquiryProduct.summarycost.toString()
              : '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('询价表明细'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          // isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(
            child: SingleChildScrollView(child: table),
          ),
        ],
      ),
    );
    return result;
  }

  _loadData() async {
    saleInquiryProduct.inquiryNo = widget.saleInquiryForm!.inquiryNo.toString();
    saleInquiryProduct.partnerId = widget.saleInquiryForm!.partnerId.toString();
    saleInquiryProduct.partnerName =
        widget.saleInquiryForm!.partnerName.toString();
    saleInquiryProduct.userId = widget.saleInquiryForm!.userId.toString();
    saleInquiryProduct.userName = widget.saleInquiryForm!.userName.toString();
    saleInquiryProduct.inquiryId = widget.saleInquiryForm!.id.toString();
    inquiryId = widget.saleInquiryForm!.id.toString();
    ResponseBodyApi responseBodyApi =
        await SaleInquiryProductOdooApi.page(data: {
      'type': 'detail',
      "page": page,
      "domainList": saleInquiryProduct.toDomainList(),
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<SaleInquiryProduct>((e) => SaleInquiryProduct.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _edit(SaleInquiryProduct? saleInquiryProduct) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleInquiryProductEdit(
          saleInquiryProduct: saleInquiryProduct,
          inquiryId: inquiryId,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _loadData();
      }
    });
  }

  _delete(List<SaleInquiryProduct> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await SaleInquiryProductOdooApi.removeByIds(ids);
      if (result.success!) {
        _loadData();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.add),
            enabled: selectedList.length == 1,
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete),
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
